const app = getApp();
const ossUrl = "https://semicon.oss-cn-shanghai.aliyuncs.com";
//const apiUrl = "https://saimian.semi.org.cn";
//const apiUrl = "https://semicon.sinocontact.com";
const apiUrl = "http://192.168.0.138:8080";

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`
}

const formatTimestamp = function(timestamp) {
  timestamp = (timestamp + (60*60*8)) * 1000;
  //timestamp = timestamp * 1000;
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = ("0" + (date.getMonth() + 1)).slice(-2);
  const day = ("0" + date.getDate()).slice(-2);
  const hours = ("0" + date.getHours()).slice(-2);
  const minutes = ("0" + date.getMinutes()).slice(-2);
  const seconds = ("0" + date.getSeconds()).slice(-2);

  return year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : `0${n}`
}

// 换行符替换为 <br/>
const nl2br = function(str) {
  return str.replace(/\r\n|\r|\n/g, '<br/>');
}

// 判断对象是否是空对象
function isEmptyObject(obj) {
  return obj != null && typeof obj === 'object' && Object.keys(obj).length === 0;
}

/* 
   日期格式化
   输入：2025/10/26 00:00:00
   输出：{
          id: '2025-10-26',
          day: '周日',
          date: '10月26日',
          yearDate: '2025年10月26日'
        }
*/
function formatDate(str) {
  // 1. 创建 Date 对象（注意：JS 的 Date 构造函数能识别 "2025/10/26" 格式）
  const date = new Date(str);

  // 2. 获取年、月、日
  const year = date.getFullYear();
  const month = date.getMonth() + 1; // getMonth() 返回 0-11
  const day = date.getDate();

  // 3. 格式化 id: 'YYYY-MM-DD'
  const id = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;

  // 4. 获取星期几（中文）
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  const dayOfWeek = weekdays[date.getDay()]; // getDay() 返回 0（周日）到 6（周六）

  // 5. 格式化 date: 'M月D日'
  const dateStr = `${month}月${day}日`;

  // 6. 格式化 date: 'Y年M月D日'
  const yearDateStr = `${year}年${month}月${day}日`;

  return {
    id,
    day: dayOfWeek,
    date: dateStr,
    yearDate: yearDateStr
  };
}


// 微信小程序wx.request封装
const ajax = function (options) {
  const accessToken = wx.getStorageSync('userToken') || ""
  // 默认参数设置
  var defaults = {
    method: "GET",
    url: "",
    data: {},
    dataType: "json",
    timeout: 10000,
    header: {
      'content-type': 'application/json', // 根据实际需求设置请求头
      'Access-Token': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySUQiOjEsIlVzZXJOYW1lIjoib3NYUmUxX0NndFJSZDFIWUlsMnR0ZXA2cmRYMCIsImlzcyI6IkF1dGhfU2VydmVyIiwic3ViIjoid2VjaGF0QXBwIiwiYXVkIjpbIldlY2hhdFVzZXIiXSwiZXhwIjoxNzYzMDI0NTI1LCJuYmYiOjE3NjI0MTk3MjUsImlhdCI6MTc2MjQxOTcyNSwianRpIjoiQVdscXZRR1Y5eSJ9.Q_k0eXOQvd-ruwVDsDz1u6JEzt1G8a0NGcPi3B9dyrM'
    },
    success: function (res) {
      // 默认成功回调
      console.log(res.data);
    },
    fail: function (err) {
      // 默认失败回调
      console.error("wxRequest error:", err);
    }
  };

  // 合并用户提供的参数和默认参数
  var settings = Object.assign({}, defaults, options);

  // 发起 wx.request
  wx.request({
    method: settings.method,
    url: settings.url,
    data: settings.data,
    dataType: settings.dataType,
    timeout: settings.timeout,
    header: settings.header,
    success: function (res) {
      // 返回1001时，登录过期
      if (res.data.code === "401") {
        console.log("401 登录过期")
        wx.removeStorageSync('uid');
        wx.removeStorageSync('userToken');
        wx.removeStorageSync('openId');
        app.globalData.uid = 0;
        app.globalData.userToken = "";
        app.globalData.openId = "";
        // wx.redirectTo({
        //   url: "/pages/index/index"  // 重定向到登录页
        // });
        return;
      }
      // 执行用户传入的 success 函数
      if (settings.success && typeof settings.success === 'function') {
        settings.success(res.data);
      }
    },
    fail: function (err) {
      // 执行用户传入的 fail 函数
      if (settings.fail && typeof settings.fail === 'function') {
        settings.fail(err);
      }
    }
  });
}

/**
 * 上传图片到后端接口
 * @param {String} tempFilePath - 通过 wx.chooseImage 获取的临时文件路径
 * @param {Object} options - 可选配置，如上传地址、额外参数等
 * @returns {Promise} - 返回上传结果
 */
const uploadImage = function (tempFilePath, options = {}, type = "") {
  const accessToken = wx.getStorageSync('userToken') || '';

  let uploadUrl = apiUrl + '/wechat_api/users/upload';
  if (type == "award_entries") { // 产品创新奖产品图
    uploadUrl = apiUrl + '/wechat_api/award_entries/upload/800/800';
  }
  
  // 默认配置
  const defaultOptions = {
    url: uploadUrl, // 默认上传接口路径
    name: 'file', // 后端接收的字段名，通常为 'file' 或 'image'
    formData: {}, // 额外表单数据
    header: {
      'Access-Token': accessToken
      // 注意：multipart/form-data 由 wx.uploadFile 自动设置，不要手动设 content-type
    }
  };

  // 合并用户传入的 options
  const config = Object.assign({}, defaultOptions, options);

  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: config.url,
      filePath: tempFilePath,
      name: config.name,
      formData: config.formData,
      header: config.header,
      success: (res) => {
        let data;
        try {
          data = JSON.parse(res.data);
        } catch (e) {
          reject({ error: 'Invalid JSON response', raw: res.data });
          return;
        }

        // 检查登录过期（和 ajax 逻辑一致）
        if (data.code === "401") {
          console.log("401 登录过期");
          wx.removeStorageSync('uid');
          wx.removeStorageSync('userToken');
          wx.removeStorageSync('openId');
          app.globalData.uid = 0;
          app.globalData.userToken = "";
          app.globalData.openId = "";
          // 可选择跳转登录页，但 Promise 中一般不跳转，由调用方处理
          reject({ code: "401", message: "登录已过期" });
          return;
        }

        if (res.statusCode === 200) {
          resolve(data);
        } else {
          reject(data);
        }
      },
      fail: (err) => {
        console.error("uploadImage fail:", err);
        reject(err);
      }
    });
  });
};

const promiseRequest = (url, data = {}, method = 'GET') => {
  const accessToken = wx.getStorageSync('userToken') || ""
  return new Promise((resolve, reject) => {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'content-type': 'application/json', // 根据实际需求设置请求头
        'Access-Token': accessToken
      },
      success: (res) => {
        if (res.statusCode === 200) {
          resolve(res.data);
        } else {
          reject(res.data);
        }
      },
      fail: (error) => {
        reject(error);
      },
    });
  });
};

module.exports = {
  ossUrl,
  apiUrl,
  ajax,
  uploadImage,
  promiseRequest,
  formatTime,
  formatTimestamp,
  nl2br,
  isEmptyObject,
  formatDate
}
